package ruralmanagementsystem.controller;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import ruralmanagementsystem.dto.HouseholdDTO;
import ruralmanagementsystem.mapper.AdminMapper;
import ruralmanagementsystem.mapper.HouseholdMapper;
import ruralmanagementsystem.pojo.Admin;
import ruralmanagementsystem.pojo.Household;
import ruralmanagementsystem.properties.JwtProperties;
import ruralmanagementsystem.result.PageResult;
import ruralmanagementsystem.result.Result;
import ruralmanagementsystem.utils.JWTUtil;
import ruralmanagementsystem.vo.AdminVO;
import ruralmanagementsystem.vo.HouseholdVO;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/account")
@CrossOrigin
@Slf4j
public class AccountController {

    @Autowired
    AdminMapper adminMapper;

    @Autowired
    HouseholdMapper householdMapper;

    @Autowired
    private JwtProperties jwtProperties;

    //管理员登录
    @PostMapping("/adminLogin")
    public Result adminLogin(@RequestBody Admin admin){
        //获取管理员输入的账号和密码
        String username = admin.getUsername();
        String password = admin.getPassword();

        //根据账号获取管理员信息
        Admin adminByUsername = adminMapper.getAdminByUsername(username);
        if(adminByUsername == null){//如果用户名不存在
            return Result.error("用户名不存在");
        }
        if(!password.equals(adminByUsername.getPassword())){
            return Result.error("密码错误！");
        }

        //登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put("tele", adminByUsername.getId());
        String token = JWTUtil.createJWT(
                jwtProperties.getAdminSecretKey(),//令牌的key
                jwtProperties.getAdminTtl(),//令牌的有效时间
                claims);
        AdminVO adminVO = new AdminVO(adminByUsername.getId(), adminByUsername.getUsername(),token);
        return Result.success(adminVO);
    }

    //村户登录
    @PostMapping("/householdLogin")
    public Result householdLogin(@RequestBody Household household){
        //获取村户输入的电话号和密码
        String holder = household.getHolder();
        String password = household.getPassword();

        //根据账号获取村户信息
        Household householdByHolder = householdMapper.getHouseholdByHolder(holder);
        if(householdByHolder == null){//如果用户名不存在
            return Result.error("用户名不存在");
        }
        if(!password.equals(householdByHolder.getPassword())){
            return Result.error("密码错误！");
        }
        //登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put("tele", householdByHolder.getHolder());
        String token = JWTUtil.createJWT(
                jwtProperties.getAdminSecretKey(),//令牌的key
                jwtProperties.getAdminTtl(),//令牌的有效时间
                claims);
        HouseholdVO householdVO = new HouseholdVO(
                householdByHolder.getId(),
                householdByHolder.getName(),
                householdByHolder.getHolder(),
                householdByHolder.getMembers(),
                householdByHolder.getField(),
                householdByHolder.getPassword(),
                token
        );
        return Result.success(householdVO);
    }

    //管理员新增村户
    @PostMapping("/addHousehold")
    public Result addHousehold(@RequestBody Household household){
        householdMapper.addHousehold(household);
        return Result.success();
    }

    //查询所有村户的详细信息
    @GetMapping()
    public PageResult getAllHousehold(HouseholdDTO householdDTO){
        PageHelper.startPage(householdDTO.getPage(), householdDTO.getPageSize());
        Page<Household> page = householdMapper.paginationQuery(householdDTO);
        List<Household> records = page.getResult();
        long total = page.getTotal();
        return new PageResult(total, records);
    }

    //查询单个村户详细信息
    @GetMapping("/{id}")
    public Result<Household> getHouseholdById(@PathVariable("id") Integer id){
        HouseholdDTO householdDTO = new HouseholdDTO();
        householdDTO.setId(id);
        householdDTO.setPage(1);
        householdDTO.setPageSize(1);
        Page<Household> page = householdMapper.paginationQuery(householdDTO);
        List<Household> records = page.getResult();
        return Result.success(records.get(0));
    }

    //根据token获取村户信息
    @GetMapping("/household")
    public Result<Household> getHouseholdByToken(HttpServletRequest request){
        String token = request.getHeader("token");
        Claims claims = JWTUtil.parseJWT("Rural", token);
        String holder = claims.get("tele").toString();
        HouseholdDTO householdDTO = new HouseholdDTO();
        householdDTO.setHolder(holder);
        householdDTO.setPage(1);
        householdDTO.setPageSize(1);
        Page<Household> page = householdMapper.paginationQuery(householdDTO);
        List<Household> records = page.getResult();
        return Result.success(records.get(0));
    }

    //查询单个管理员详细信息
    @GetMapping("/admin")
    public Result<Admin> getAdminByToken(HttpServletRequest request){
        String token = request.getHeader("token");
        Claims claims = JWTUtil.parseJWT("Rural", token);
        Integer adminId = Integer.parseInt(claims.get("tele").toString());
        Admin adminById = adminMapper.getAdminById(adminId);
        return Result.success(adminById);
    }

    //修改管理员信息
    @PutMapping("/admin")
    public Result updateAdminByToken(@RequestBody Admin admin){
        adminMapper.updateAdmin(admin);
        return Result.success();
    }

    //根据id修改村户信息
    @PutMapping()
    public Result updateHousehold(@RequestBody Household household){
        householdMapper.updateHousehold(household);
        return Result.success();
    }

    //根据id删除村户
    @DeleteMapping("/{id}")
    public Result deleteHousehold(@PathVariable("id") Integer id){
        householdMapper.deleteHousehold(id);
        return Result.success();
    }
}

